package com.tungse.juc.lock;

import lombok.SneakyThrows;

import java.util.concurrent.TimeUnit;

/**
 * @author Tungse
 * 死锁
 */
public class DeadLock_Demo {
    public static void main(String[] args) {

        new Thread(new DeadLock("lockA","lockB"),"t1").start();
        new Thread(new DeadLock("lockB","lockA"),"t2").start();
    }
}

class DeadLock implements Runnable{

    private String lockA;
    private String lockB;

    public DeadLock(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @SneakyThrows
    @Override
    public void run() {
        synchronized (lockA){
            System.out.println(Thread.currentThread().getName()+"\t"+"自己持有："+lockA+"，希望获得："+lockB);
            TimeUnit.SECONDS.sleep(2);

            synchronized (lockB){
                System.out.println(Thread.currentThread().getName()+"\t"+"自己持有："+lockB+"，希望获得："+lockA);
            }
        }
    }
}